#include "../include/client.h"

//保存断点信息
int save_breakpoint(const char* filename, off_t offset, int filesize){

    breakPoint_t bp = {0};

    strncpy(bp.filename,filename,sizeof(bp.filename)-1);
    bp.offset = offset;
    //如果offset >= filesize，说明已经传输完毕；
    //如果<，则表示未传输完
    bp.status = (offset>= filesize)?1:0;

    char bp_filename[4112] = {0};
    //将原始文件名 filename 与 .bp 后缀拼接，生成新的文件名
    snprintf(bp_filename,sizeof(bp_filename),"%s.bp",filename);
    int bp_file_fd = open(bp_filename,O_WRONLY|O_CREAT|O_TRUNC,0666);
    ERROR_CHECK(bp_file_fd,-1,"open bp_filename fail");

    //将断点信息写入
    write(bp_file_fd, &bp, sizeof(breakPoint_t));
    //‘write’ reading 4112 bytes from a region of size 8 [-Wstringop-overread]
    close(bp_file_fd);
    return 0;
}

//加载断电信息
int load_breakpoint(const char* filename, breakPoint_t bp){

    bzero(&bp,sizeof(breakPoint_t));
    char bp_filename[4096] = {0};
    snprintf(bp_filename,sizeof(bp_filename),"%s.bp",filename);
    int bp_file_fd = open(bp_filename,O_WRONLY|O_CREAT|O_TRUNC,0666);
    ERROR_CHECK(bp_file_fd,-1,"open bp_filename fail");

    int ret = read(bp_file_fd,&bp,sizeof(breakPoint_t));
    ERROR_CHECK(ret,-1,"read breakPoint fail");

    if(bp.status == 1){
        printf("文件已经传输完毕，无需续传！\n");
    }
    printf("加载断点：%s,已经传输 = %ld 字节,总大小= %d 字节",bp.filename,bp.offset,bp.filesize);
    close(bp_file_fd);
    return 0;
}



